package terra.twl.widget;

import java.io.IOException;

import terra.Loader;
import terra.definitions.item.ArmorDef;
import terra.definitions.item.ItemDef;
import terra.definitions.item.WeaponDef;
import terra.managers.DefManager;
import terra.managers.ResourceManager;
import terra.model.ItemClientDef;
import terra.slick.GameState;
import terra.twl.window.CraftPanel;
import terra.twl.window.IDropable;
import de.matthiasmann.twl.AnimationState;
import de.matthiasmann.twl.Color;
import de.matthiasmann.twl.Event;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.Label;
import de.matthiasmann.twl.ThemeInfo;
import de.matthiasmann.twl.renderer.AnimationState.StateKey;
import de.matthiasmann.twl.renderer.Image;
import de.matthiasmann.twl.renderer.Texture.Rotation;

/**
 *
 * @author Matthias Mann
 */
public class ItemSlot extends Label {
    
    public static final StateKey STATE_DRAG_ACTIVE = StateKey.get("dragActive");
    public static final StateKey STATE_DROP_OK = StateKey.get("dropOk");
    public static final StateKey STATE_DROP_BLOCKED = StateKey.get("dropBlocked");
    
    public ItemClientDef def;
    public Image icon;
    public Image defaultIcon;
    private IDropable listener;
    private boolean dragActive;

    public ItemSlot() {
    }

    public boolean canDrop() {
        return def == null;
    }
    
    public Image getIcon() {
        return icon;
    }
    
    public IDropable getListener() {
        return listener;
    }

    public void setListener(IDropable listener) {
        this.listener = listener;
    }
    
    public void setDropState(boolean drop, boolean ok) {
        AnimationState as = getAnimationState();
        as.setAnimationState(STATE_DROP_OK, drop && ok);
        as.setAnimationState(STATE_DROP_BLOCKED, drop && !ok);
    }
    
    @Override
    protected boolean handleEvent(Event evt) {
        if(evt.isMouseEventNoWheel()) {
        	if (evt.getType() == Event.Type.MOUSE_BTNUP)
	        	if (def != null && evt.getMouseButton() == Event.MOUSE_RBUTTON){
	        		if (!(getParent() instanceof CraftPanel))
	        			GameState.getInstance().inventory.useItem(def.getOId(), def.getId());
	        		else
	        			reset();
	        		return true;
	        	}
            if(dragActive) {
                if(evt.isMouseDragEnd()) {
                    if(listener != null) {
                        listener.dragStopped(this,evt.getMouseX(),evt.getMouseY(),null, null);
                      //  System.out.println("dragStopped");
                    }
                    dragActive = false;
                    getAnimationState().setAnimationState(STATE_DRAG_ACTIVE, false);
                } else if(listener != null) {
                    listener.dragging(this,evt.getMouseX(),evt.getMouseY());
                    //System.out.println("dragging");
                }
            } else if(evt.isMouseDragEvent()) {
                dragActive = true;
                getAnimationState().setAnimationState(STATE_DRAG_ACTIVE, true);
                if(listener != null) {
                    listener.dragStarted(this,evt.getMouseX(),evt.getMouseY());
                   // System.out.println("dragStarted");
                }
            }
            return true;
        }
        return super.handleEvent(evt);
    }

    @Override
    protected void paintWidget(GUI gui) {
    	if (def != null && icon == null){
    		try {
    			//System.out.println(ResourceManager.getPath(DefManager.allItems.get(def.getId()).image));
				icon = (Image) gui.getRenderer().loadTexture(
						Loader.class.getResource(ResourceManager.getPath(DefManager.allItems.get(def.getId()).image).substring(6)), "RGBA", "linear").
									getImage(0, 0, 32, 32, Color.WHITE, false, Rotation.NONE);
			} catch (IOException e) {e.printStackTrace();}
    	}
        if(!dragActive && icon != null) {
            icon.draw(getAnimationState(), getInnerX(), getInnerY(), getInnerWidth(), getInnerHeight());
            if (def != null && DefManager.allItems.get(def.getId()).isStackable)
            	getFont().drawText(null, getInnerX()-2, getInnerY()+18, def.getCount()+"");
        } else if (icon == null && defaultIcon != null)
        	defaultIcon.draw(getAnimationState(), getInnerX(), getInnerY(), getInnerWidth(), getInnerHeight());
    }

    @Override
    protected void paintDragOverlay(GUI gui, int mouseX, int mouseY, int modifier) {
        if(icon != null) {
            final int innerWidth = getInnerWidth();
            final int innerHeight = getInnerHeight();
            icon.draw(getAnimationState(),
                    mouseX - innerWidth/2,
                    mouseY - innerHeight/2,
                    innerWidth, innerHeight);
        }
    }

    @Override
    protected void applyTheme(ThemeInfo themeInfo) {
        super.applyTheme(themeInfo);
    }

	public void reset() {
		icon = null;
		def = null;
		setTooltipContent(getThemeTooltipContent());
	}

	public void setDef(ItemClientDef def2){
		def = def2;
		ItemDef d = DefManager.allItems.get(def.getId());
		String tooltip = "Name: "+d.name + (d.tooltip != "" ? "\nTooltip: "+ d.tooltip : "");
		if (d instanceof WeaponDef){
			tooltip +="\n\nAttack: " + ((WeaponDef)d).damage;
			tooltip +="\nRange: " + ((WeaponDef)d).radius;
			tooltip +="\nCritPower: " + ((WeaponDef)d).getFloatProperty("critRate");
			tooltip +="\nCritChance: " + Math.round(((WeaponDef)d).getFloatProperty("critChance")*100);
			tooltip +="\nType: " + WeaponDef.getStringForType(((WeaponDef)d).type);
		} else if (d instanceof ArmorDef){
			tooltip +="\n\nArmor: " + ((ArmorDef)d).armor;
		}
		tooltip += "\nWeight: " + d.weight;
		setTooltipContent(tooltip);
	}
    
}
